import Fly from './wx'
// import {
//   baseURL
// } from '../config'

const fly = new Fly()
let app = getApp()

// 基本配置
//本机开发环境
//fly.config.baseURL = 'http://127.0.0.1:48080' // api的base_url
//生产环境
fly.config.baseURL = 'https://api.fudaojiapu.com:8889' // api的base_url
fly.config.timeout = 60000 // 超时设置为60秒

fly.config.headers = {
    'reqcode': 'wx',
  // X_AUTH_MANAGER_ID: 0
}

// request拦截器
fly.interceptors.request.use(request => {
  if (!app) {
    app = getApp()
  }

  wx.showNavigationBarLoading()
  // // 随机数
  // request.headers['ZY_TRANSID'] = Math.random()
  //   .toString(36)
  //   .substr(2)
  // request.headers['ZY_SHOP_ID'] = app.shopId
  // // token
  request.headers['Authorization'] = 'Bearer '+(app.userInfo && app.userInfo.token || '');
  request.headers['uid'] = app.userInfo && app.userInfo.id || '';
  // // 地理位置
  // let location = app.location || {};
  // request.headers['ZY_LAT'] = location.latitude || ''
  // request.headers['ZY_LNG'] = location.longitude || ''
  // // 打开场景值
  // request.headers['ZY_SCENE'] = app.appScene
  // // appid
  // request.headers['ZY_WX_ID'] = app.appid
  // // 版本号
  // request.headers['ZY_APPVERSION'] = app.version

  // // build号
  // request.headers['ZY_APPBUILD'] = app.buildNumber
  // // 手机型号
  // // request.headers['ZY_MACHINECODE'] = app.systemInfo.model
  // // 手机品牌
  // request.headers['ZY_MACHINETYPE'] = app.systemInfo.model
  // // 系统类型
  // request.headers['ZY_SYSTEMTYPE'] = app.systemInfo.platform
  // // 系统版本

  // let sv = app.systemInfo.system;
  // let svArr = sv.split(" ");
  // if (sv.length > 1) sv = svArr[1];
  // request.headers['ZY_SYSTEMVERSION'] = sv
  // // 屏幕宽
  // request.headers['ZY_SCREENWIDTH'] = app.systemInfo.screenWidth
  // // 屏幕高
  // request.headers['ZY_SCREENHEIGHT'] = app.systemInfo.screenHeight
  // // 分辨率
  // request.headers['ZY_SCREENDENSITY'] = app.systemInfo.pixelRatio
  // // 语言
  // request.headers['ZY_LOCALIZATION'] = app.systemInfo.language

  // //小程序码携带的渠道
  // let qrCodeChannel = app.qrCodeChannel;
  // if (qrCodeChannel && qrCodeChannel.channel && qrCodeChannel.expire) {
  //   let nowT = +new Date();
  //   if (nowT <= qrCodeChannel.expire) {
  //     request.headers['ZY_CHANNEL'] = qrCodeChannel.channel;
  //   } else {
  //     app.qrCodeChannel = '';
  //     wx.clearStorage("qrCodeChannelKey");
  //   }
  // }

  // request.headers['X_AUTH_UID'] = app.userInfo ? app.userInfo.id || 0 : 0

  // 返回数据类型
  if(request.method === 'JSON_POST'){
    request.method='POST'
    request.headers['Content-Type'] = 'application/json'
    if (request.data) {
      request.data = JSON.stringify(request.data)
    }
  } else if (request.method === 'POST') {
    request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    if (request.data) {
      request.data = JSON.stringify(request.data)
    }
  } else if (request.method === 'LOGINPOST') {//登录特殊处理
    request.method='POST'
  }
  return request
})

// respone拦截器
fly.interceptors.response.use(
  (response, promise) => {
    console.log(response);
    wx.hideNavigationBarLoading()
    let code = response.data.code

    // 正常
    if (code === 0 || code === -1) {
      return promise.resolve(
        JSON.parse(
          JSON.stringify(response.data).replace(
            /\u00A0|\u2028|\u2029|\uFEFF/g,
            ''
          )
        )
      )
    }

    wx.hideLoading(); //事先隐藏loading

    // data中设置了错误不弹框(错误时优先级最高)
    if (response.request.body.hideErrMsg === 'hideErrMsg' || response.request.body.hideErrMsg === true) {

      return Promise.reject(response.data)
    }

    // 用户未登录、未注册统一到登录页面
    if (code === 401) {
      // 清除登录状态
      // app.clearLoginStatus()
        // let currentPage = getCurrentPages().pop()
        // if (currentPage.route !== 'pages/my/login/index') {
          wx.navigateTo({
            url: '/pages/login/index?autoRegister=true'
          })
        // }

      return Promise.reject(response.data)
    }
    if(code===12005){
      wx.navigateTo({
        url: '/pages/vip/index',
      })
      return Promise.reject(response.data)
    }
    if (code === 100001 && response.request.url == "saas/user/w/wechat/qrcode/create") {
      // 您的小程序未发布,无法导出二维码 错误不弹框
      return
    }

    wx.showToast({
      title: response.data.message || '请求接口错误',
      icon: 'none',
      duration: 3000
    })
    return Promise.reject(response.data)
  },
  error => {
    wx.hideNavigationBarLoading()
    wx.getNetworkType({
      success: function(res) {
        if (res.networkType == 'none') {
          wx.showToast({
            title: '请检查网络连接',
            icon: 'none',
            duration: 3000
          })
        } else {
          wx.showToast({
            title: '请求接口失败',
            icon: 'none',
            duration: 3000
          })
        }
      }
    })
    return Promise.reject(error)
  }
)

export default fly